<script lang="ts" setup>
import { allowedUserTypes, getUserInfo } from '@/api/login/userLogin'
import { ExperimentOutlined, FileTextOutlined, HomeOutlined, ReadOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { getUserMeta } from '@/api/PersonalSpace/PersonalInfo'

// 控制 Drawer 的显示状态（如果需要）
// const drawerVisible = ref(false)
const router = useRouter()

// 定义用户类型和权限
const userType = ref<string | null>(null)
const canPublishCourse = ref(false)

// 获取用户信息的函数
const fetchUserInfo = async () => {
  try {
    const response = await getUserInfo()
    userType.value = response.userType
    if (userType.value && allowedUserTypes.includes(userType.value))
      canPublishCourse.value = true
  }
  catch (error) {
    console.error('API 调用错误:', error)
    message.error('无法获取用户信息，请稍后重试。')
  }
}

const userAvatar = ref<string | null>(null)

const fetchUserAvatar = async () => {
  const response = await getUserMeta()
  userAvatar.value = response.userImage
}

// 在组件挂载时调用获取用户信息的函数
onMounted(() => {
  fetchUserInfo()
  fetchUserAvatar()
})

// 删除所有 Cookies 的函数
const deleteAllCookies = () => {
  const cookies = document.cookie.split(';')
  cookies.forEach((cookie) => {
    const eqPos = cookie.indexOf('=')
    const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie
    document.cookie = `${name}=; Max-Age=0; path=/; domain=${window.location.hostname}`
    document.cookie = `${name}=; Max-Age=0; path=/`
  })
}

// 处理登出
const handleLogout = () => {
  router.push('/login')
  deleteAllCookies()
  localStorage.clear()
  sessionStorage.clear()
  message.success('已登出')
}

// 跳转到教师发布课程页面
const handleTeacher = () => {
  router.push('/teacher/manage/course/course')
}

const openDocumentation = () => {
  window.open('https://pcnrs799f5t6.feishu.cn/docx/YclwdsVcsouMEVxdfpFc5euMnYQ?from=from_copylink', '_blank')
}

// 跳转到首页
const handleHomepageSquare = () => {
  router.push('/user/homepagesquare')
}

// 定义路由-标题对照表，里面应该是 path 为正则表达式，title 为标题
const routeTitleMap = [
  {
    path: /^\/user\/homepagesquare$/,
    title: '首页',
  },
  {
    path: /^\/user\/training$/,
    title: 'AI+X训练营',
  },
  {
    path: /^\/user\/smartEducation$/,
    title: 'AI+智慧教育',
  },
  {
    path: /^\/user\/innovation\/project$/,
    title: '双创广场 | 项目展示',
  },
  {
    path: /^\/user\/innovation\/project\/(\d+)$/,
    title: '双创广场 | 项目展示 | 项目详情',
  },
  {
    path: /^\/user\/innovation\/competition$/,
    title: '双创广场 | 赛事信息',
  },
  {
    path: /^\/user\/innovation\/competition\/(\d+)$/,
    title: '双创广场 | 赛事信息 | 竞赛详情',
  },
  {
    path: /^\/user\/learningNew\/skill-tree$/,
    title: '学习广场 | 技能树',
  },
  {
    path: /^\/user\/learningNew\/skill-tree\/(\d+)$/,
    title: '学习广场 | 技能树 | 技能详情',
  },
  {
    path: /^\/user\/learningNew\/course$/,
    title: '学习广场 | 课程',
  },
  {
    path: /^\/user\/learningNew\/course\/(\d+)\/(\d+)$/,
    title: '学习广场 | 课程 | 课程详情',
  },
  {
    path: /^\/user\/practice$/,
    title: '实训广场',
  },
  {
    path: /^\/user\/model$/,
    title: '模型广场',
  },
  {
    path: /^\/user\/model\/(\d+)$/,
    title: '模型广场 | 模型详情',
  },
  {
    path: /^\/user\/data$/,
    title: '数据广场',
  },
  {
    path: /^\/user\/data\/(\d+)$/,
    title: '数据广场 | 数据详情',
  },
  {
    path: /^\/user\/application\/dev-space$/,
    title: '应用广场',
  },
  {
    path: /^\/user\/science$/,
    title: '科研广场',
  },
  {
    path: /^\/micro-scene\/area/,
    title: 'AI+X专区',
  },
]

// 计算属性，根据当前页面路由获取页面标题
const pageTitle = computed(() => {
  // 获取当前路由
  const currentRoute = router.currentRoute.value
  // 获取当前路由的标题
  const title = routeTitleMap.find(item => item.path.test(currentRoute.path))?.title
  // 如果找不到那么就是空字符串
  return title || ''
})
</script>

<template>
  <a-layout-header style="display: flex;align-items: center; justify-content: flex-end; align-content: center; background-color: #ffffff; height: 50px; background-color: rgba(255, 255, 255, 0); padding-inline: 20px; padding-top: 16px;">
    <div class="flex items-center justify-between w-full">
      <div class="left-section">
        <span class="text-sm font-bold">
          {{ pageTitle }}
        </span>
      </div>
      <div class="right-section flex items-center">
        <slot name="right-section">
          <!-- 教师端 - 仅在 canPublishCourse 为 true 时显示 -->
          <div class="flex items-center">
            <div
              v-if="canPublishCourse"
              class="icon-with-text text"
              @click="handleTeacher"
            >
              <ReadOutlined class="icon" />
              <span class="text">发布课程</span>
            </div>

            <!-- icon 跳转 -->
            <div class="icon-with-text" @click="openDocumentation">
              <FileTextOutlined class="icon" />
              <span class="text">使用说明</span>
            </div>

            <div class="icon-with-text" @click="handleHomepageSquare">
              <HomeOutlined class="icon" />
              <span class="text">首页</span>
            </div>
          </div>
        </slot>

        <!-- 头像下拉菜单 -->
        <a-dropdown placement="bottomRight">
          <template #overlay>
            <a-menu class="dropdown-menu">
              <!-- 退出登录菜单项 -->
              <a-menu-item key="logout" class="flex-1 text-center" @click="handleLogout">
                退出登录
              </a-menu-item>
            </a-menu>
          </template>
          <!-- 展示下拉菜单的头像 -->
          <a-avatar :src="userAvatar" style="cursor: pointer" />
        </a-dropdown>
      </div>
    </div>
    <!-- <MessageDrawer :visible="drawerVisible" @close="closeDrawer" /> -->
  </a-layout-header>
</template>

<style scoped lang="scss">
.title-link {
  text-decoration: none;
  color: inherit;

  &:hover {
    color: #1890ff !important;
    transition: color 0.3s ease;
  }
}

.dropdown-menu {
  // 深度选择ant-dropdown-menu-title-content
  :deep(.ant-dropdown-menu-title-content) {
    font-size: 0.875rem;
  }
}

.logo {
  height: 2.5rem;
  margin-right: 0.25rem;
  object-fit: contain;
}

.title {
  color: rgb(0, 0, 0);
  font-size: 1.5rem;
  font-weight: bold;
}

.icon-with-text {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  margin-right: 1rem;

  .icon {
    font-size: 1rem;
  }

  .text {
    font-size: 0.875rem;
    line-height: 1;
  }
}
</style>
